package com.huqs.smoothphotoview.library.download;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;


/**
 * 图片下载
 */
public class DownLoadImageService implements Runnable {
    private String url;
    private Context context;
    private final ImageDownLoadCallBack mCallBack;
    private File currentFile;
    private boolean isExist=false;
    public DownLoadImageService(Context context, String url, final ImageDownLoadCallBack callBack) {
        this.url = url;
        this.mCallBack = callBack;
        this.context = context;
        File file;
        file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsoluteFile();//注意小米手机必须这样获得public绝对路径
        String fileName;
        File appDir = new File(file.getPath());
        String splits[] = url.split("/");
        fileName = splits[splits.length - 1];
        String filePath = appDir.getPath() + "/" + fileName;
        File file2 = new File(filePath);
        if (file2.exists()) {
            if ( context instanceof Activity){
                ((Activity)context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mCallBack.onFileExists();
                    }
                });
            }

            this.isExist=true;
        }
    }

    @Override
    public void run() {
        if (this.isExist)return;
        if ( context instanceof Activity){
            ((Activity)context).runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mCallBack.onStart();
                }
            });
        }
        File file = null;
        Bitmap bitmap = null;
        try {
            bitmap = Glide.with(context)
                    .load(url)
                    .asBitmap()
                    .into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                    .get();
            if (bitmap != null) {
                // 在这里执行图片保存方法
                saveImageToGallery(context, bitmap, url);
            }
        } catch (Exception e) {
            if ( context instanceof Activity){
                ((Activity)context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mCallBack.onDownLoadFailed();
                    }
                });
            }


        }
    }

    public void saveImageToGallery(Context context, Bitmap bmp, String url) {
        // 首先保存图片
        File file;
        file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsoluteFile();//注意小米手机必须这样获得public绝对路径
        String fileName;
        File appDir = new File(file.getPath());
        if (!appDir.exists()) {
            appDir.mkdirs();
        }
        String splits[] = url.split("/");
        fileName = splits[splits.length - 1];
        currentFile = new File(appDir, fileName);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(currentFile);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            if ( context instanceof Activity){
                ((Activity)context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mCallBack.onDownLoadSuccess();
                    }
                });
            }
        } catch (FileNotFoundException e) {
            if ( context instanceof Activity){
                ((Activity)context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mCallBack.onDownLoadFailed();
                    }
                });
            }
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
            if ( context instanceof Activity){
                ((Activity)context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mCallBack.onDownLoadFailed();
                    }
                });
            }
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                Uri.fromFile(new File(currentFile.getPath()))));
    }
}